package com.iuchannel.android.provider.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;

/**
 * This class returns the result String of HttpPost
 * 
 * @author Yohan Chang
 *
 */
public class PostHttp{

	/**
	 * 
	 * @param url
	 * @return String
	 */
	public static String postUrlEx(String url){
		OutputStreamWriter wr=null;
		BufferedReader rd=null;
		String postUrl=url;
		String result="";
		try{
	        URL urlCon = new URL(url);
	        URLConnection conn = urlCon.openConnection();
	        // If you invoke the method setDoOutput(true) on the URLConnection, it will always use the POST method.
	        conn.setDoOutput(true);
	        wr = new OutputStreamWriter(conn.getOutputStream());
	        wr.write(postUrl);
	        wr.flush();
	    
	        // Get the response
	        rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
	        String line;
	        String data_line="";
	        while ((line = rd.readLine()) != null) {
	        	result=result+line;
	        }				
		}catch(Exception e){
			
		}
		
		return result;
	
	}
	
	/**
	 * 
	 * @param url
	 * @return String
	 */
	public static String postUrl(String url){
		return postUrlEx(url);
		//return postUrl(url, "");
	}
	/**
	 * 
	 * @param url
	 * @param cookie
	 * @return String
	 */
	public static String postUrl(String url, String cookie){
		String result="";
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost post = null;
			post = new HttpPost(url);
			
			if(cookie!=null && cookie.length()>0){
				try{
					URI uri = new URI(url);
					String urlDomain=uri.getHost();
					urlDomain=urlDomain.startsWith("www.")?urlDomain.substring(4):urlDomain;
					
			    	CookieStore cookieStore = new BasicCookieStore();
			        String[] cookie_parts = cookie.split(";");
			        for(int t=0;t < cookie_parts.length;t++){
			            String[] cookieContent = cookie_parts[t].split("=");
			            Cookie tempCookie = new BasicClientCookie(cookieContent[0],cookieContent[1]);
			            ((BasicClientCookie) tempCookie).setDomain(urlDomain);
			            cookieStore.addCookie(tempCookie);
			        }
			        httpclient.setCookieStore(cookieStore);						
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			//get.setHeader("Cookie",cookie);
			HttpResponse response = httpclient.execute(post);
			
			
			// get Result
			HttpEntity resEntity = response.getEntity();

			InputStream is = resEntity.getContent();
			InputStreamReader reader = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(reader);
			String temp = "";
			if ((temp = br.readLine()) != null) {
				result += temp;
			}

			br.close();
			is.close();
			
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return result;
	}	
	
}